use hypers::prelude::{hook, Next, Request, Responder,Error};
use crate::controller::{request_base_url,error_response_json,error_admin_html,AppState};
use crate::APP_STATE;

//  权限检测
#[hook]
pub async fn auth(mut req: Request, next: &mut Next<'_>) -> impl Responder {
    let login_id = req.remove::<u32>("login_id").unwrap();
    let state = req.remove::<AppState>(APP_STATE).unwrap();
    if login_id <= 0 {
        let message = "请先登陆";
        let url = format!("{}{}",request_base_url(&req),"admin/auth/login");
        if req.method().as_str().eq("POST") {
            return Ok::<_,Error>(error_response_json(message));
        } else {
            return Ok::<_,Error>(error_admin_html(&state,message, &url));
        }
    }
    return next.next(req).await
}
